package com.bite.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@SpringBootTest
public class JWTUtilsT {
    private static long expiration =30*60*1000;//30分钟过期
    private static String secretString = "rkFbhl8tfnnKOC/rVQCHc1MTOUTSAbwXWLdZ5t3wsJs";
    private static  Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
    @Test
    public void genJwt() {
        Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode("rkFbhl8tfnnKOC/rVQCHc1MTOUTSAbwXWLdZ5t3wsJs"));
        Map<String,Object> data = new HashMap<>();
        data.put("id",1);
        data.put("name","zhangsan");

        String compact = Jwts.builder()
                .setClaims(data)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .signWith(key)
                .compact();
        System.out.println(compact);
    }
    @Test
    void genKey() {
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String encode = Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(encode);
    }
    @Test
    void verify() {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiemhhbmdzYW4iLCJpZCI6NSwiZXhwIjoxNzI1Mzc4Mzk2fQ.RhlR7jalG8KE_g0KPxLjjLlJUM5xmcuK5cslIHN3okU";
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = build.parseClaimsJws(token).getBody();
        System.out.println(body.get("id"));
        System.out.println(body.get("name"));
    }
    @Test
    public void genJwt2() {
        Map<String,Object> data = new HashMap<>();
        data.put("id",1);
        data.put("name","zhangsan");
        System.out.println(JwtUtils.genJwt(data));

    }



}
